package memento.generalv1;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author：LJ
 * @Description：
 * @Date: 2017/12/1
 * @Modified By:
 */
public class BeanUtils {

    public static Map<String, Object> backupProp(Object bean) {
        Map<String, Object> result = new HashMap<String, Object>();

        try {
            //BeanInfo 描述
            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
            //获得属性描述
            PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor p : properties) {
                //属性名称
                String proName = p.getName();
                //读取属性的方法
                Method getter = p.getReadMethod();
                //读取属性值
                Object fieldValue = getter.invoke(bean, new Object[]{});
                //遍历所有属性
                if (!proName.equalsIgnoreCase("class"))
                    result.put(proName, fieldValue);
            }

        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void restoreProp(Object bean, Map<String, Object> map) {
        try {
            //BeanInfo 描述
            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
            //获得属性描述
            PropertyDescriptor[] ps = beanInfo.getPropertyDescriptors();
            //遍历所有属性
            for (PropertyDescriptor p : ps) {
                //属性名称
                String proName = p.getName();
                //如果有这个属性
                if (map.containsKey(proName)) {
                    //写属性的方法
                    Method method = p.getWriteMethod();
                    method.invoke(bean, new Object[]{map.get(proName)});
                }
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
